package com.sinodoggo.shitcloud.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sinodoggo.shitcloud.commons.Constants;
import com.sinodoggo.shitcloud.commons.Result;
import com.sinodoggo.shitcloud.entity.RoleMenu;
import com.sinodoggo.shitcloud.exception.ServiceException;
import com.sinodoggo.shitcloud.service.IRoleMenuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sinodoggo
 * @since 2022-11-22
 */
@RestController
@RequestMapping("/role-menu")
public class RoleMenuController {
    @Resource
    private IRoleMenuService roleMenuService;

    @Transactional
    @PostMapping("/{roleId}")
    public Result setMenusForRoles(@PathVariable Integer roleId, @RequestBody List<Integer> menuIds) {
        // 清除原有对应关系
        boolean result = roleMenuService.removeBatchByRoleId(roleId);
        if (result) {
            // 重设授权对应关系
            for (Integer menuId : menuIds) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menuId);
                roleMenuService.save(roleMenu);
            }
            return Result.success();
        } else {
            throw new ServiceException(Constants.CODE_500, "重设授权关系时发生错误!");
        }
    }

    @GetMapping("/{roleId}")
    public Result getMenusByRoleId(@PathVariable Integer roleId) {
        QueryWrapper<RoleMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId);
        final List<RoleMenu> roleMenuList = roleMenuService.list(wrapper);
        return Result.success(roleMenuList);
    }
}

